package com.ignou.mca.evote;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ignou.mca.datasource.DataBaseUtilities;
import com.ignou.mca.util.SessionUtil;

public class UserActivation extends HttpServlet {
	public void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		DataBaseUtilities dbu = new DataBaseUtilities();
		Connection conn = dbu.getConnection();
		PrintWriter out;
		ServletContext context = getServletContext();
		
		int i = 0;
		try {
			PreparedStatement pstmt;
			Statement stmt = conn.createStatement();
			ResultSet rs;
			out = res.getWriter();
			String activationCode = req.getParameter("activationCode");
			String activationEmail = "";
			String activationUser = req.getParameter("userName");

			String query = "select activationdate,activestatus,email,username from users where randomnumber='"
					+ activationCode.trim()+ "' AND userName='"+activationUser+"'";

			rs = stmt.executeQuery(query);
			Calendar now1 = Calendar.getInstance();
			Calendar now = Calendar.getInstance();
			SimpleDateFormat dayformat = new SimpleDateFormat("MM/dd/yyyy");
			Date d = new Date();

			String date = null;
			Date d1 = null;

			if (rs.next()) {
				Date d2 = rs.getDate(1);
				if(d2==null) d2 = new Date();
				date = dayformat.format(d2);
				activationEmail = rs.getString(3);
				d1 = new Date(date + " " + rs.getTime(1));
				now1.setTime(d1);
				pstmt = conn.prepareStatement("update users set activeStatus=?,activationdate=? where randomnumber=?");
				pstmt.setString(1,"active");
				pstmt.setString(2, getCurrentDate());
				pstmt.setString(3, activationCode.trim());

				long h = (now.getTime().getTime()) - (now1.getTime().getTime());
				long t = h / (60 * 1000);
				if (t <= 1440) {
					if (rs.getBoolean(2)) {
						req.setAttribute("UserErrorMessage","User Already activated.");
						context.getRequestDispatcher("/UserErrors.jsp").forward(req, res);
					} else {
						i = pstmt.executeUpdate();
						if (i == 1) {
							SessionUtil.sendMail(activationEmail, activationUser, "", "registersuccess","");
							context.getRequestDispatcher("/Login.jsp").forward(req, res);
						}
					}
				} else {

					if (rs.getBoolean(2)) {
						req.setAttribute("UserErrorMessage","User Already activated.");
						context.getRequestDispatcher("/UserErrors.jsp").forward(req, res);;
					} else {
						pstmt = conn.prepareStatement("delete from users where randomnumber=?");
						pstmt.setString(1, activationCode.trim());
						i = pstmt.executeUpdate();
						req.setAttribute("UserErrorMessage","Activation has expired and user details deleted.");
						context.getRequestDispatcher("/UserErrors.jsp").forward(req, res);
					}
				}
			}else
			{
				req.setAttribute("UserErrorMessage","The activation you entered is wrong. Please check and try again.");
				context.getRequestDispatcher("/UserErrors.jsp").forward(req, res);
			}

		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("UserErrorMessage","An error has occured while collecting information. please try again later.");
			context.getRequestDispatcher("/UserErrors.jsp").forward(req, res);
		}

	}

	private static String getCurrentDate() {
		// TODO Auto-generated method stub
		Date currentDate = new java.util.Date();

		java.sql.Date sqlDate = new java.sql.Date(currentDate.getTime());
		// System.out.println("date"+sqlDate);

		return sqlDate + " " + currentDate.getHours() + ":"
				+ currentDate.getMinutes() + ":" + currentDate.getSeconds()
				+ ".0";
	}

}
